package com.siashan.unipay4j.wx.splitbill;

import com.siashan.unipay4j.core.IPayConfig;
import com.siashan.unipay4j.core.Result;
import com.siashan.unipay4j.core.UnipayConst;
import com.siashan.unipay4j.core.splitbill.ISplitBillQuery;
import com.siashan.unipay4j.core.splitbill.ProfitQueryModel;
import com.siashan.unipay4j.wx.AbstractWxPay;
import com.siashan.unipay4j.wx.WxBizEnum;
import com.siashan.unipay4j.wx.sdk.WXPayConstants;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信分账查询
 *
 * @author siashan
 * @since v1.0.1
 **/
public class WxPaySplitBillQuery extends AbstractWxPay implements ISplitBillQuery {
    public WxPaySplitBillQuery() {
    }

    public WxPaySplitBillQuery(IPayConfig payConfig) {
        super(payConfig);
    }


    /**
     * 分账结果查询
     *
     * @param model  查询参数
     * @return 分账结果
     */
    @Override
    public Result query(ProfitQueryModel model) {
        try {
            Map<String, String> r = initWxPay().sendRequest(wrapParam(model), WXPayConstants.PROFITSHARINGQUERY_URL_SUFFIX, WxBizEnum.SPLITBILL, true);
            String returnCode = getReturnCode(r);
            if (isReturnSuccess(returnCode)) {
                if (isResultSuccess(r)) {
                    return Result.tradeSuccess(r);
                } else {
                    String errCode = r.get(WXPayConstants.ERR_CODE);
                    String errCodeDes = r.get(WXPayConstants.ERR_CODE_DES);
                    return Result.returnFail(errCode, errCodeDes);
                }
            } else {
                String returnMsg = r.get(WXPayConstants.RETURN_MSG);
                return Result.returnFail(returnCode, returnMsg);
            }

        } catch (Exception e) {

        }
        return Result.exception();
    }

    /**
     * 封装查询参数
     *
     * @param model 查询请求参数
     * @return 查询参数
     */
    private Map<String, String> wrapParam(ProfitQueryModel model) {
        Map<String, String> map = new HashMap<>();
        map.put("transaction_id", model.getTradeNo());
        map.put("out_order_no", model.getOutTradeNo());
        return map;
    }
}
